from flask import current_app, jsonify
from flask import redirect
from flask import request
from flask import session
from flask import url_for

from info import constants, db
from info.models import User, News
from info.utils.response_code import RET
from . import admin_blu
from flask import render_template


@admin_blu.route("/login",methods=["POST","GET"])
def login():
    if request.method == "GET":
        user_id = session.get("user_id",None)
        is_admin = session.get("is admin",False)
        if user_id and is_admin:
            return render_template("admin/index.html")
        return render_template("admin/login.html")
    # 1、获取参数判空
    username = request.form.get("username")
    password = request.form.get("password")
    if not all([username,password]):
        return render_template("admin/login.html", errmsg="参数错误")
    # 2、查询数据库， 看是否有该用户
    try:
        user= User.query.filter(User.mobile == username).first()
    except Exception as e:
        current_app.logger.error(e)
        return render_template("admin/login.html", errmsg="数据库查询失败")
    if not user:
        return render_template("admin/login.html", errmsg="用户不存在")
    # 3、校验密码是否正确
    if not user.check_passowrd(password):
        return render_template("admin/login.html", errmsg="密码错误")
    # 4、校验是否是管理员
    if user.is_admin != 1:
        return render_template("admin/login.html", errmsg="用户权限不足")
    # 5、保存用户登陆信息到session
    session["user_id"] = user.id
    session["nick_name"] = user.nick_name
    session["mobile"] = user.mobile
    session["is_admin"] = True
    # 6、登录成功重定向到管理员首页
    return redirect(url_for("admin.index"))


@admin_blu.route("/index")
def index():
    return render_template("admin/index.html")


@admin_blu.route("/user_count")
def user_count():
    return render_template("admin/user_count.html")


@admin_blu.route("/news_review")
def news_review():
    # 1.获取参数
    p = request.args.get("p",1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1
    filters = [News.status != 0]
    keywords = request.args.get("keywords", None)
    if keywords:
        filters.append(News.title.contains(keywords))
    # 2.查询数据库
    try:
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(p,constants.ADMIN_NEWS_PAGE_MAX_COUNT)
        news_list = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
    new_dict_list = []
    for i in news_list:
        new_dict_list.append(i.to_review_dict())
    data = {"new_dict_list":new_dict_list,"current_page":current_page,"total_page":total_page}

    # 3.操作成功，返回数据
    return render_template("admin/news_review.html",data=data)


@admin_blu.route('/news_review_detail/<int:news_id>')
def news_review_detail(news_id):
    try:
        news = News.query.get(news_id)
    except Exception as e:
        return jsonify(errno=RET.DBERR, errmsg="数据库查询失败")
    if not news:
        return jsonify(errno=RET.NODATA, errmsg="没有这篇新闻")
    data = {"news":news.to_dict()}
    return render_template("admin/news_review_detail.html",data=data)


@admin_blu.route("/news_review_active", methods=["POST"])
def news_review_active():
    # 1.获取参数，判空
    data_dict = request.json
    action = data_dict.get("action")
    news_id = data_dict.get("news_id")
    if not all([action, news_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    if action not in ("accept", "reject"):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    # 2.判断新闻是否存在
    try:
        news = News.query.get(news_id)
    except Exception as e:
        return jsonify(errno=RET.DBERR, errmsg="数据库查询失败")
    if not news:
        return jsonify(errno=RET.NODATA, errmsg="没有这篇新闻")
    # 3、判断action的值
    if action == "accept":
        news.status = 0
    else:
        reason = data_dict.get("reason")
        if not reason:
            return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
        news.status = -1
        news.reason = reason
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="数据库操作失败")
    # 4.返回成功
    return jsonify(errno=RET.OK, errmsg="操作成功")
